This set of exercises is meant to help you practice some of the concepts we learned in week 1. Your challenge at the end of class was to make a line drawing, extrapolate vectors of x, y coordinates from it, and then plot it in R.
Pencil and paper are great coding tools. Sketch your ideas, draw diagrams, and try to set some expectations for what you might see. Using any sort of ruled paper, you can map out plotting decisions and think about how to organize your data to fit within the plot’s dimensions.
Let’s go with some basic shapes and then ramp up the complexity. What you are supposed to see here is that vectors are counts, measurements, and coordinates alike. We can store, call, and plot this data in a lot of different ways. Let’s see the basic process in action.
draw_me <- list(x = c(1, 1, 2, 2), y = c(1, 2, 2, 1)) #We're just putting our two vectors into a list here.
plot(draw_me)
#Can be more verbose...
x = c(1, 1, 2, 2)
y = c(1, 2, 2, 1)
plot(x, y)
Since we’re drawing shapes, we’re going to set the plot type argument to line plot (type = “l”).
plot(draw_me,
type = "l")
Our square isn’t complete! It’s also hard to appreciate its squareness because of the framing of the plot (R always cuts it as close as possible to the outside of the object). If we want to make the lines connect, we need to come back to the starting location again, so we need 5 positions to draw our square.
draw_me <- list(x = c(1, 1, 2, 2, 1),
y = c(1, 2, 2, 1, 1)) #We're just putting our two vectors into a list here.
plot(draw_me,
type = "l",
xlim = c(0,3), #Adding plotting arguments "xlim =" and "ylim =", which allow us to define the plot window.
ylim = c(0,3))
Drawing some shapes from our imagination is easy enough. We can also do a hexagon using 7 digits. Below, we also label the points with the text() function. This function works with plot() and allows us to add text to the plot window. For this function, we need to feed it x and y coordinates as well as a string of labels.
draw_me <- list(x = c(1, 2, 4, 5, 4, 2, 1),
y = c(2, 4, 4, 2, 0, 0, 2)+1)
plot(draw_me,
type = "l",
xlim = c(0,6),
ylim = c(0,6))
text(draw_me$x, #We are using text() here. We give it the same x coordinates as the drawing.
draw_me$y+0.1, #We give it the same y coordinates, but add a constant so the numbers sit just above the line segments.
labels = 1:7) #We add an integer label up to 7.
And octagons with 9 digits.
draw_me <- list(x = c(1, 1, 2, 3, 4, 4, 3, 2, 1),
y = c(1, 2, 3, 3, 2, 1, 0, 0, 1))
plot(draw_me,
type = "l",
xlim = c(0,5),
ylim = c(0,5))
text(draw_me$x,
draw_me$y+0.1,
labels = 1:length(draw_me$x))
Using a pad and paper, we can map out the outline of a star. I’m including a picture from my phone as well as a sketch of my work below with plot().
knitr::include_graphics("images/star.png")